package controls;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.JsonObject;

import util.LogTable;

import dao.Database;

import model.Log;

/**
 * Servlet implementation class LogServlet
 */
@WebServlet("/LogServlet")
public class LogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// private Map<String,Map<String,Integer>> pairMap = null;
	// private Map<String,Integer> opCount = null;
	// private Integer pairCount = null;
	private LogTable logTable = null;

	Log log = new Log();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LogServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		logTable = (LogTable) request.getServletContext().getAttribute("logTable");

		// request.gets

		String type = request.getParameter("type");
		String operator = request.getParameter("operator");
		//String sel = request.get
		//System.out.println("seleted Item"+sel);

		Database db = new Database();

		JsonObject ret = null;
		
		if (type.equals("add")) {
			ret = log.add(operator, logTable);
		} else if (type.equals("store")) {
			System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
			try {
				logTable.pairCount += log.store(type, db.getConnection(),
						logTable.pairMap,logTable);
				// System.out.println("sizeesss:"+logTable.pairCount);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		out.println(ret);

		// request.setAttribute("pairLog", pairMap);
		// request.setAttribute("opcountMap", opCount);
		// request.setAttribute("paircount", pairCount);

		System.out.println(request.getParameter("type"));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
